package com.tange.ai.iot.client.gnssa.view

// VerticalSeekBar.kt
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View

class VerticalSeekBar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private var progress = 50
    private var max = 100
    private var cornerRadius = 20f
    private var barWidth = 40f
    private var progressColor = 0xFF2196F3.toInt()

    private val backgroundPaint = Paint().apply {
        color = 0xFFBBDEFB.toInt()
        style = Paint.Style.FILL
        isAntiAlias = true
    }

    private val progressPaint = Paint().apply {
        color = progressColor
        style = Paint.Style.FILL
        isAntiAlias = true
    }

    private var progressChangeListener: OnProgressChangeListener? = null

    interface OnProgressChangeListener {
        fun onProgressChanged(progress: Int)
    }

    fun setOnProgressChangeListener(listener: OnProgressChangeListener) {
        progressChangeListener = listener
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val width = MeasureSpec.getSize(widthMeasureSpec)
        val height = MeasureSpec.getSize(heightMeasureSpec)
        setMeasuredDimension(width, height)
        barWidth = width.toFloat()
        cornerRadius = barWidth / 4
    }

    override fun onDraw(canvas: Canvas) {
        // 绘制背景
        val backgroundRect = RectF(0f, 0f, barWidth, height.toFloat())
        canvas.drawRoundRect(backgroundRect, cornerRadius, cornerRadius, backgroundPaint)

        // 计算进度高度
        val progressHeight = height * progress / max
        val progressTop = height - progressHeight

        // 绘制进度
        val progressRect = RectF(0f, progressTop.toFloat(), barWidth, height.toFloat())
        canvas.drawRoundRect(progressRect, cornerRadius, cornerRadius, progressPaint)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> {
                val y = height - event.y
                progress = (y / height * max).coerceIn(0F, max.toFloat()).toInt()
                progressChangeListener?.onProgressChanged(progress)
                invalidate()
                return true
            }
        }
        return super.onTouchEvent(event)
    }

    fun setProgress(progress: Int) {
        this.progress = progress.coerceIn(0, max)
        invalidate()
    }

    fun getProgress() = progress

    fun setMax(max: Int) {
        this.max = max
        invalidate()
    }

    fun getMax() = max
}